import router from './router'
import store from './store'
import {Message} from 'element-ui'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import {getCheckedMenuIds} from 'src/utils/common'

import {getToken} from 'src/utils/auth'
import getPageTitle from 'src/utils/get-page-title'

import {tooltipHide} from "./tooltipHideMethod"

NProgress.configure({showSpinner: false})

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {

    NProgress.start()

    document.title = getPageTitle(to.meta.title)

    const hasToken = getToken()
    if (hasToken) {
        if (to.path === '/login') {
            // next({path: '/'})
            next()
            NProgress.done()
        } else {
            const hasMenu = store.getters.menu && store.getters.menu.length > 0
            if (hasMenu) {
                // console.log(to.matched)
                if(to.matched && to.matched.length>0){
                    next()
                }else{
                    // console.log(123)
                    next(`/error/404`)
                }

            } else {
                try {
                    const { menu } = await store.dispatch('user/getInfo')

                    let ids = getCheckedMenuIds(menu, [])

                    // const accessRoutes = await store.dispatch('permission/generateRoutes', ids)
                    const accessRoutes = await store.dispatch('permission/generateRoutes', menu)
                    router.addRoutes(accessRoutes)
                    next({ ...to, replace: true })
                } catch (error) {
                    await store.dispatch('user/resetToken')

                    Message.closeAll()
                    Message({
                        type:'error',
                        message: error || "Has Error"
                    })

                    next(`/login?redirect=${to.path}`)
                    NProgress.done()
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login?redirect=${to.path}`)
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    tooltipHide()
    window.sessionStorage.clear()
    NProgress.done()
})
